from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse

from selenium import webdriver
import time

# Create your views here.
def show_index(request):
    template = loader.get_template('archive.html')
    html = template.render({'download_url':"未检测到"})
    return HttpResponse(html)



def archive(request):

    download_url =get_download_url(request)
    
    template = loader.get_template('archive.html')
    html = template.render({'download_url':download_url})
    return HttpResponse(html)


def archive_ajax(request):
    download_url =get_download_url(request)
    return HttpResponse(download_url)



def get_download_url(request):
    # pageNumber = request.GET.get('pageNumber',1) 
    # 从post中取得数据，如果不存在则默认值为1 
    musicUrl = request.GET.get('music_url',"http://www.kugou.com/song/#hash=CC91E0A5046A116F11E41571C76E099B&album_id=579779") 
    
    option = webdriver.ChromeOptions()
    option.add_argument("headless")
    browser = webdriver.Chrome(chrome_options=option)

    download_url = ""
    try:
        browser.get(musicUrl)
        time.sleep(1)
        myAudio = browser.find_element_by_id('myAudio')
        download_url = myAudio.get_attribute('src')
        print(download_url)
    finally:
        browser.close()
        
    return download_url 